package jp.seraph.same.model;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.NullArgumentException;

import jp.seraph.jsade.model.Align;
import jp.seraph.jsade.model.JointIdentifier;
import jp.seraph.jspf.pose.DefaultPose;

public class PoseJointModel implements JointModel {
    public PoseJointModel(DefaultPose aPose, JointIdentifier aIdentifier, Align aAlign, int aOrder, double aMaxDgree, double aMinDgree) {
        mBasePose = aPose;
        mIdentifier = aIdentifier;
        mAlign = aAlign;
        mOrder = aOrder;
        mMaxValue = aMaxDgree;
        mMinValue = aMinDgree;
        mListeners = new ArrayList<JointModelListener>();
    }

    private List<JointModelListener> mListeners;
    private DefaultPose mBasePose;
    private JointIdentifier mIdentifier;
    private Align mAlign;
    private int mOrder;
    private double mMaxValue;
    private double mMinValue;

    public void addListener(JointModelListener aListener) {
        if (aListener == null)
            throw new NullArgumentException("aListener");

        mListeners.add(aListener);
    }

    public Align getJointAlign() {
        return mAlign;
    }

    public double getJointAngleAsDegree() {
        return mBasePose.getJointAngle(mIdentifier).getDegree();
    }

    public JointIdentifier getJointIdentifier() {
        return mIdentifier;
    }

    public String getJointName() {
        return mIdentifier.toJointName();
    }

    public int getJointOrder() {
        return mOrder;
    }

    public double getMaxAngleAsDegree() {
        return mMaxValue;
    }

    public double getMinAngleAsDegree() {
        return mMinValue;
    }

    public boolean removeListener(JointModelListener aListener) {
        int tCount = mListeners.size();
        for (int i = 0; i < tCount; i++) {
            if (mListeners.get(i).equals(aListener)) {
                mListeners.remove(i);
                return true;
            }
        }

        return false;
    }

    public void setJointAngleAsDegree(double aDegree) {
        double tCurrent = mBasePose.getJointAngle(mIdentifier).getDegree();
        if (tCurrent != aDegree) {
            mBasePose.setJointAngle(mIdentifier, aDegree);
            onJointAngleChanged();
        }
    }

    protected void onJointAngleChanged() {
        for (JointModelListener tListener : mListeners) {
            tListener.JointAngleChanged(this);
        }
    }

}
